package com.diandi.activity.service.impl;

import com.diandi.activity.bean.*;
import com.diandi.activity.manager.ActivityManager;
import com.diandi.activity.service.ActivityWebService;
import com.diandi.ddsb.bean.*;
import com.diandi.ddsb.vo.*;
import com.diandi.utils.DateUtil;
import com.diandi.utils.NumberUtil;
import freemarker.template.utility.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * Created by a on 2018/3/20.
 */
@RestController
public class ActivityWebServiceImpl implements ActivityWebService {
    private static NumberFormat nf = NumberFormat.getNumberInstance();
    @Autowired
    private ActivityManager activityManager;
    @Override
    public List<Activity> queryActivitys(@RequestParam Map<String, Object> paramMap) {
        List<Activity> activities = activityManager.queryActivitys(paramMap);
        for (Activity activity : activities) {
            if (activity.getRewardPoint() == RewardPointType.invest_send_hb.getValue()
                    || activity.getRewardPoint() == RewardPointType.INVEST_ACTIVITY.getValue()
                    || activity.getRewardPoint() == RewardPointType.RE_INVEST_ACTIVITY.getValue()
                    || activity.getRewardPoint() == RewardPointType.TOTAL_INVEST_ACTIVITY.getValue()
                    || activity.getRewardPoint() == RewardPointType.INVEST_BY_PERIOD.getValue()
                    || activity.getRewardPoint() == RewardPointType.HQB_EXIT_ACTIVITY.getValue()) {
                String publishPlatforms = "";
                String[] strs = activity.getPublishPlatforms().split(",");
                for (String str : strs) {
                    publishPlatforms += PublishPlatformType.getTextByValue(Integer.parseInt(str)).getText() + "|";
                }
                activity.setPublishPlatforms(publishPlatforms);
                String borrowTypes = "";
                String[] strs_ = activity.getBorrowTypes().split(",");
                for (String str : strs_) {
                    borrowTypes += BorrowTypes.getTextByValue(Integer.parseInt(str)).getText() + "|";
                }
                activity.setBorrowTypes(borrowTypes);
            }
            if (activity.getSend() != null && activity.getGenerateNum() != null) {
                activity.setSendSituation(activity.getSend() + "/" + activity.getGenerateNum());
            }
            if (activity.getRegisterEnd().getTime() < new Date().getTime() && activity.getStatus() == 1) {
                activity.setInvalidReason(1);// 已经过期
            } else if (activity.getRegisterEnd().getTime() < new Date().getTime() && activity.getStatus() == 2) {
                activity.setInvalidReason(2);// 已经过期且手工修改失效
            } else {
                activity.setInvalidReason(0);
            }
        }
        return activities;
    }

    @Override
    public Integer queryActivitysCount(@RequestParam  Map<String, Object> paramMap) {
        return activityManager.queryActivitysCount(paramMap);
    }

    @Override
    public Results addNewInvestActivity(@RequestBody NewActivityInfoVo activity) {
        return activityManager.addNewInvestActivity(activity);
    }


    @Override
    public Map<String , Object> getDetailMV(Long id, String editFlag) {
        Map<String , Object> mv = new HashMap<String , Object>();
        ActivityInfoVo vo = activityManager.getActivityById(id);
        vo.setId(id);
        vo.setInviteNodeText(null == vo.getInviteNode() ? "" : InviteNodeType.getTextByValue(vo.getInviteNode())
                .getText());
        // 已 html的行形式 拼前台显示活动已关联的列表
        if (vo.getTickets() != null) {
            StringBuffer showlotteryTicket = new StringBuffer();
            for (LotteryTicket ticket : vo.getTickets()) {
                showlotteryTicket.append("<tr><td colspan=2>");
                String startTimeVal = DateUtil.formatDateToStr(DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS,
                        ticket.getStartTime());
                String endTimeVal = DateUtil.formatDateToStr(DateUtil.FORMAT_YYYY_MM_DD_HH_MM_SS, ticket.getEndTime());
                String borrowTypes = "";
                if (isNotBlank(ticket.getBorrowTypes())) {
                    String[] strs_ = ticket.getBorrowTypes().split(",");
                    for (String str : strs_) {
                        borrowTypes += BorrowTypes.getTextByValue(Integer.parseInt(str)).getText() + "|";
                    }
                }
                // 加息券
                if (ticket.getType() == LotteryTicketType.ADDINTEREST_TICKET.getValue()) {
                    showlotteryTicket.append("奖池Id:" + ticket.getId() + ":券加息率"
                            + NumberUtil.doubleDivide(ticket.getAddInterestRate(), 0.01d, 2) + "%,生效时间" + startTimeVal
                            + " 至 " + endTimeVal);
                    if (ticket.getMaxInvestAmount() == null) {
                        showlotteryTicket.append(",最大投资金额无限制," + borrowTypes + "可用 ");
                    } else {
                        showlotteryTicket.append(",最大投资金额" + ticket.getMaxInvestAmount() + "元," + borrowTypes + "可用 ");
                    }
                }
                // 体验金
                else if (ticket.getType() == LotteryTicketType.EXPERIENCE_TICKET.getValue()) {
                    if (ticket.getAmount() != null) {
                        showlotteryTicket.append("奖励" + ticket.getId() + ":体验券金额" + ticket.getAmount() + "元,生效时间"
                                + startTimeVal + " 至 " + endTimeVal);
                    } else if (ticket.getMaxInvestAmount() != null) {
                        showlotteryTicket
                                .append("奖池Id:" + ticket.getId() + ":体验券金额上限" + nf.format(ticket.getMaxInvestAmount())
                                        + "元,生效时间" + startTimeVal + " 至 " + endTimeVal);
                    } else {
                        showlotteryTicket.append("奖池Id:" + ticket.getId() + ":体验券金额无上限,生效时间" + startTimeVal + " 至 "
                                + endTimeVal);
                    }
                }
                // 现金红包
                else if (ticket.getType() == LotteryTicketType.CASH_PACKAGE.getValue()) {
                    if (ticket.getAmount() != null) {
                        showlotteryTicket.append("奖池Id:" + ticket.getId() + ":固定金额" + ticket.getAmount() + "元,生效时间"
                                + startTimeVal + " 至 " + endTimeVal);
                    } else {
                        if(ticket.getTasteType() == TasteType.INVEST_DAYS.getValue() || ticket.getTasteType() == TasteType.INVEST_MULTIPLE.getValue()){
                            showlotteryTicket.append("奖池Id:" + ticket.getId() + ":返现比例"
                                    + NumberUtil.doubleDivide(ticket.getInvestBackRate(), 0.01d, 2) + "%,生效时间"
                                    + startTimeVal + " 至 " + endTimeVal);
                        }else if(ticket.getTasteType() == TasteType.INVEST_APR.getValue() || ticket.getTasteType() == TasteType.INVEST_MULTIPLE.getValue()){
                            showlotteryTicket.append("奖池Id:" + ticket.getId() + ":返现天数"
                                    + ticket.getAddInterestDays() + "天,生效时间"
                                    + startTimeVal + " 至 " + endTimeVal);
                        }
                    }
                }
                // 积分券
                else if (ticket.getType() == LotteryTicketType.INTEGRAL_TICKET.getValue()) {
                    if (ticket.getIntegralType() == IntegralType.FIXED_INTEGRAL.getValue()) {
                        showlotteryTicket.append("奖池Id:" + ticket.getId() + ":固定积分" + ticket.getAmount() + ",生效时间"
                                + startTimeVal + " 至 " + endTimeVal);
                    } else if (ticket.getIntegralType() == IntegralType.FORMULA_INTEGRAL.getValue()) {
                        BigDecimal integralRatio = null == ticket.getIntegralRatio() ? BigDecimal.ONE : ticket
                                .getIntegralRatio();
                        BigDecimal integralParamOne = null == ticket.getIntegralParamOne() ? BigDecimal.ONE : ticket
                                .getIntegralParamOne();
                        BigDecimal integralParamTwo = null == ticket.getIntegralParamTwo() ? BigDecimal.ONE : ticket
                                .getIntegralParamTwo();

                        showlotteryTicket.append("奖池Id:" + ticket.getId() + ":积分公式:(投资金额或借款金额)*" + integralRatio + "/"
                                + integralParamOne + "*" + integralParamTwo + ",生效时间" + startTimeVal + " 至 "
                                + endTimeVal);
                    } else {
                        showlotteryTicket.append("奖池Id:" + ticket.getId() + ":按公式计算,生效时间" + startTimeVal + " 至 "
                                + endTimeVal);
                    }
                }
                // 其他
                else {
                    showlotteryTicket.append("奖池Id:" + ticket.getId() + ":券金额" + ticket.getAmount() + "元,生效时间"
                            + startTimeVal + " 至 " + endTimeVal);
                    showlotteryTicket.append(",使用门槛" + ticket.getInvestMiniAmount() + "元," + borrowTypes + "可用 ");
                }
                showlotteryTicket.append("</td></tr>");
                vo.setTicketId(ticket.getId());
            }
            mv.put("lotteryTickets", showlotteryTicket);
        }
        mv.put("editFlag", editFlag);
        mv.put("activityInfoVo", vo);
        if (vo.getRewardPoint() == RewardPointType.invest_send_hb.getValue()) {
            mv.put("viewName","activity/activityIndexTZSHB");
        } else if (vo.getRewardPoint() == RewardPointType.invitation.getValue()) {
            mv.put("viewName","activity/activityIndexYQ");
        } else if (vo.getRewardPoint() == RewardPointType.LUCK_DRAW.getValue()
                || vo.getRewardPoint() == RewardPointType.MJ_TURN_TABLE.getValue()
                || vo.getRewardPoint() == RewardPointType.FREE_DRAW.getValue()) {

            mv.put("ruleList", activityManager.queryRuleByActivityId(id));
            mv.put("prizeList", activityManager.queryPrizeByActivityId(id));
            mv.put("viewName","activity/activityIndexLuck");
        } else if (vo.getRewardPoint() == RewardPointType.INVEST_ACTIVITY.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexNewInvest");
        } else if (vo.getRewardPoint() == RewardPointType.HQB_EXIT_ACTIVITY.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexHQBExit");
        } else if (vo.getRewardPoint() == RewardPointType.NEW_INVITATION_ACTIVITY.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexXYQ");
        } else if (vo.getRewardPoint() == RewardPointType.RE_INVEST_ACTIVITY.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexCashBack");
        } else if (vo.getRewardPoint() == RewardPointType.TOTAL_INVEST_ACTIVITY.getValue()) {
            mv.put("viewName","activity/activityIndexTotalInvest");
        } else if (vo.getRewardPoint() == RewardPointType.EGG_TURN_TABLE.getValue()) {
            mv.put("ruleList", activityManager.queryRuleByActivityId(id));
//            mv.addObject("prizeList", activityManager.queryEggPrizeByActivityId(id));砸蛋奖励后续添加
            mv.put("viewName","activity/eggDrawActivityDetail");
        } else if (vo.getRewardPoint() == RewardPointType.INVEST_BY_PERIOD.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);
            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/periodInvestDetail");
        }else if (vo.getRewardPoint() == RewardPointType.LOAN_SEND_INTEGRAL.getValue()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexLoan");
        } else if (RewardPointType.SIGN_ACTIVITY.getValue() == vo.getRewardPoint()) {
            ActivityRule activityRule = new ActivityRule();
            activityRule.setActivityId(id);

            mv.put("ruleList", activityManager.queryActRuleByEntity(activityRule));
            mv.put("viewName","activity/activityIndexSign");
        } else {
            mv.put("viewName","activity/activityIndex");
        }
        return mv;
    }
    @Override
    public Result updateActivity(@RequestBody Activity activity) {
        return activityManager.updateActivity(activity);
    }
    @Override
    public Map<String, Object> queryActivityInfoForStatistics(@RequestParam("activityid") long activityId) {
        Map<String, Object> data = new HashMap<String, Object>();

        Activity activity = activityManager.getActivityById(activityId);

        if (null == activity)
            return data;

        String borrowTypes = activity.getBorrowTypes();
        String[] borrowType = new String[30];

        if (StringUtils.isNotBlank(borrowTypes)) {
            borrowType = StringUtil.split(borrowTypes, ',');
        }

        List<ComboboxDataVO> borrowTypesList = new ArrayList<ComboboxDataVO>();
        for (String type : borrowType) {
            if (StringUtils.isBlank(type))
                continue;

            ComboboxDataVO vo = new ComboboxDataVO();
            vo.setValue(Integer.valueOf(type));
            vo.setText(BorrowTypes.getTextByValue(Integer.valueOf(type)).getText());
            borrowTypesList.add(vo);
        }
        data.put("borrowTypes", borrowTypesList);

        String publishPlatForms = activity.getPublishPlatforms();
        String[] platForm = new String[3];
        if (StringUtils.isNotBlank(publishPlatForms)) {
            platForm = StringUtil.split(publishPlatForms, ',');
        }

        List<ComboboxDataVO> platFormList = new ArrayList<ComboboxDataVO>();
        for (String type : platForm) {
            if (StringUtils.isBlank(type))
                continue;
            ComboboxDataVO vo = new ComboboxDataVO();
            vo.setValue(Integer.valueOf(type));
            vo.setText(PublishPlatformType.getTextByValue(Integer.valueOf(type)).getText());
            platFormList.add(vo);
        }
        data.put("platForms", platFormList);

        List<ComboboxDataVO> periodsList = activityManager.queryInvestPeriodsComboxData(activityId);
        data.put("periodsList", periodsList);

        List<Map<String, Object>> ticketInfo = activityManager.queryInvestTicketsSendInfo(activityId);

        for (Map<String, Object> map : ticketInfo) {
            Integer type = (int) map.get("type");
            map.put("typeName", LotteryTicketType.getTextByValue(type).getText());
        }

        data.put("ticketInfo", ticketInfo);
        Map<String, Object> m = activityManager.queryInvestInfo(activityId);
        if(m!=null)
            data.putAll(m);
        //替换活动总投资额
        Map<String, Object> map = activityManager.queryActTotalInvestAmount(activityId);
        if(map !=null)
            data.putAll(map);

        return data;
    }
    @Override
    public List<InvestActStasticsInfoVo> queryInvestStatisticsInfoByCondition(@RequestParam Map<String, Object> condition) {
        List<InvestActStasticsInfoVo> dataList = activityManager.queryInvestStatisticsInfoByCondition(condition);
        if(CollectionUtils.isEmpty(dataList)){
            return dataList;
        }
		/*投资集合包，奖券使用明细表中的 borrow_invest_id 为其中一个标的的投资记录，
		 * 需要根据  投资记录表中的 freeeze_no 关联出该笔订单的所有投资记录，
		 * 把所有投资加和替换到 InvestActStasticsInfoVo.amount，展示到前端*/
        List<String> param  = new ArrayList<String>();
        for (InvestActStasticsInfoVo vo : dataList) {
            //判断是否是集合包
            if(vo.getIsInPackage()==null||vo.getIsInPackage()!= 1||vo.getTradeNo() ==null){
                continue;
            }
            param.add(vo.getTradeNo());
        }
        List<PackageInvestTotalAmount> pInvestAmount = null;
        if(!CollectionUtils.isEmpty(param)){
            condition.clear();
            condition.put("tradeNoList", param);
            pInvestAmount = activityManager.queryPackageTotalInvestAmount(condition);
        }
        if(!CollectionUtils.isEmpty(pInvestAmount)){
            for (InvestActStasticsInfoVo vo : dataList) {
                if(vo.getIsInPackage()==null||vo.getIsInPackage()==0){
                    continue;
                }
                for (PackageInvestTotalAmount pVo : pInvestAmount) {
                    String tr = pVo.getTradeNo();
                    String investFreezeNo = vo.getTradeNo();
                    //集合包，修改投资金额,修改投资类型
                    if(tr!=null&& investFreezeNo !=null && tr.equals(investFreezeNo)){
                        vo.setAmount(pVo.getPackageInvsetAmount());
                        vo.setInvestType(BorrowTypes.ACT_PACKAGE.getValue());
                        break;
                    }
                }
            }
        }
        return dataList;
    }
    @Override
    public Integer queryInvestStatisticsInfoCountByCondition(@RequestParam Map<String, Object> condition) {
        return activityManager.queryInvestStatisticsInfoCountByCondition(condition);
    }
}